<template>
  <div class="table">
    <div class="content-common">
      <div class="header-title">同比各月降雨量</div>
      <!-- 顶部搜索条件-->
      <div class="search-top">
        <el-form :label-position="'top'" :inline="true" :model="query">
          <el-form-item label="站点类型">
            <el-select style="width: 160px" v-model="query.stType" filterable clearable placeholder="请选择" :disabled="isView" @change="typeChange">
              <el-option v-for="item in stTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="站点名称">
            <el-select style="width: 160px" v-model="query.stcd" filterable clearable placeholder="请选择">
              <el-option v-show="item.stType == query.stType" v-for="item in stationData" :key="item.stcd" :label="item.stnm" :value="item.stcd"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起讫年份">
            <year-range-picker :yearRange="query.yearRange" @yearChanged="handleYearChanged"></year-range-picker>
          </el-form-item>
        </el-form>
      </div>
      <!-- 数据预览文字 -->
      <div class="data-preview">
        <div v-for="(item, index) in tableData" :key="index" :class="`preview-item item-${index}`" :style="`background-color: ${bgColors[index]};`">
          <div class="preview-item-text">
            总降水量 <span class="total">{{ item.drp }}</span> mm，降雨天数 <span class="">{{ item.rainDays }}</span> 天；最大月降水量 <span>{{ item.maxMonthDrp }}</span> mm({{ item.maxMonth }})，
            最大日降水量 <span>{{ item.maxDailyDrp }}</span> mm({{ item.maxDay }})，最大次雨量 <span>{{ item.maxSeqDrp }}</span> mm，历时 <span>{{ item.maxSeqDuration }}</span> min， 最大30min雨强
            <span>{{ item.maxI30 }}</span> mm/h({{ item.maxI30Date }})，最大次降雨侵蚀力 <span>{{ item.maxEi30 }}</span> MJmm/(hm²·h)({{ item.maxEi30Date }})， 年降雨侵蚀力为
            <span class="total">{{ item.yearEi30 }}</span> MJ.mm/(hm².h)。
          </div>
          <el-button :style="`background-color:${colors[index]}`" round>{{ item.year }}</el-button>
        </div>
      </div>
      <!-- 数据预览表格 -->
      <div class="table">
        <table>
          <tr>
            <th style="width: 162px">
              <div class="oline"><span class="span1">指标</span> <span class="span2">年份</span></div>
            </th>
            <th>降水量<br />（mm）</th>
            <th>降雨天数<br />（d）</th>
            <th>最大月<br />降雨量（mm）</th>
            <th>最大日<br />降雨量（mm）</th>
            <th>最大次<br />降雨量（mm）</th>
            <th>最大次<br />降雨历时（min）</th>
            <th>最大30min<br />雨强（mm/h）</th>
            <th>最大次降雨侵蚀力<br />（MJ.mm/(hm²)）</th>
            <th>年降雨侵蚀力<br />（MJ.mm/(hm².h)）</th>
          </tr>
          <tr v-for="(item, index) in tableData" :key="index">
            <td>{{ item.year }}</td>
            <td>{{ item.drp }}</td>
            <td>{{ item.rainDays }}</td>
            <td>{{ item.maxMonthDrp }}</td>
            <td>{{ item.maxDailyDrp }}</td>
            <td>{{ item.maxSeqDrp }}</td>
            <td>{{ item.maxSeqDuration }}</td>
            <td>{{ item.maxI30 }}</td>
            <td>{{ item.maxEi30 }}</td>
            <td>{{ item.yearEi30 }}</td>
          </tr>
        </table>
      </div>
      <!-- 数据预览图表 -->
      <div id="mychart" ref="mychart" style="width: 100%; height: 490px"></div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import {
  sysdictviewlistDictItem,
  listRainfallYearCount, //列表查询降雨年统计
  viewPageStationInfo,
  listRainfallMonthCount
} from '../../../api/index';
import YearRangePicker from '../../../components/common/YearRangePicker.vue';
export default {
  name: 'zhengbianguancao',
  components: { YearRangePicker },
  data() {
    return {
      globalUser: [],
      page: {
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
        totalSize: 0
      },
      query: {
        stcd: JSON.parse(sessionStorage.getItem('userInfo')).stcdList[0].stcd,
        stType: 1,
        yearRange: [`${new Date().getFullYear()}` - 1, `${new Date().getFullYear()}`]
      },

      formInline: {},
      tableData: [],
      logTitle: '',
      pageTotal: 0,
      stationData: [],
      checkArr: [],
      tijiaoform: {
        status: 1
      },
      isView: false,
      dialogMes: {
        show: false,
        query: {}
      },
      stTypeList: [
        { label: '坡面径流场', value: 1 },
        { label: '小流域控制站', value: 2 }
      ],
      bgColors: ['hsla(215, 100%, 71%, 0.2)', 'hsla(106, 67%, 58%, 0.2)'], //图示颜色
      colors: ['#69A8FF', '#6DDC4C'], //图示颜色
      monthData: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    };
  },
  created() {
    this.globalUser = globalUser;
    this.query.year = globalyear;
    this.getData();
    this.getMonthData();
    this.getstationData();
    this.getchecktype();
  },
  watch: {
    'query.yearRange': {
      //选择年份
      handler(newVal) {
        if (newVal) {
          this.getData();
          this.getMonthData();
        }
      }
    },
    'query.stcd': {
      //站点名称
      handler(newVal) {
        if (newVal) {
          this.getData();
          this.getMonthData();
        }
      }
    },
    'query.stType': {
      //站点类型
      handler(newVal) {
        if (newVal) {
          this.getData();
          this.getMonthData();
        }
      }
    }
  },
  methods: {
    handleYearChanged(val) {
      this.query.yearRange = val;
    },
    // 获取数据
    getData() {
      let yearBegin = this.query.yearRange[0] || '';
      let yearEnd = this.query.yearRange[1] || '';
      if (yearBegin === '') {
        return this.$message.error('请选择开始年份!');
      }
      if (yearEnd === '') {
        return this.$message.error('请选择结束年份!');
      }
      let data = {
        stcd: this.query.stcd || '',
        stType: this.query.stType || 1,
        yearBegin: yearBegin,
        yearEnd: yearEnd
      };
      //   获取数据
      listRainfallYearCount(data).then((res) => {
        this.tableData = res.object;
      });
    },
    getMonthData() {
      let yearBegin = this.query.yearRange[0] || '';
      let yearEnd = this.query.yearRange[1] || '';
      let data = {
        stcd: this.query.stcd || '',
        stType: this.query.stType || 1,
        yearBegin: yearBegin,
        yearEnd: yearEnd
      };
      //   获取数据
      listRainfallMonthCount(data).then((res) => {
        const _data = res.object;
        for (let i = 0; i < _data.length; i++) {
          let tmp = Object.entries(_data[i]).map(([key, d]) => {
            if (d.length > 0) {
              let obj = {
                label: key,
                value: d,
                children: []
              };
              return obj;
            } else {
              return {
                label: key,
                value: d
              };
            }
          });
          _data[i].arr = tmp.filter((e) => {
            return e.label !== 'year';
          });
        }
        for (let i = 0; i < _data.length; i++) {
          _data[i].data = this.getResultData(_data[i].arr);
        }
        this.initChart(_data);
      });
    },
    getResultData(arr) {
      let result = [];
      for (let i = 0; i < arr.length; i++) {
        result.push(arr[i].value);
      }
      return result;
    },
    initChart(arr) {
      var myChart = echarts.init(document.getElementById('mychart'));
      let option = {
        title: {
          text: '降雨量：mm',
          textStyle: {
            fontFamily: 'PingFangSC, PingFang SC',
            fontSize: 14,
            color: '#252B46',
            fontWeight: 400
          }
        },
        tooltip: {},
        legend: {
          icon: 'pin',
          textStyle: {
            color: '#252B46',
            fontSize: 14,
            fontWeight: 400,
            height: 32,
            lineHeight: 32
          }
        },
        grid: {
          left: 50,
          right: 0
        },
        xAxis: {
          data: this.monthData,
          minorSplitLine: {
            show: false
          },
          axisTick: { show: false },
          axisLine: { show: false },
          axisLabel: {
            margin: 55,
            fontFamily: 'PingFangSC, PingFang SC',
            fontSize: 14,
            color: '#252B46'
          },
          splitLine: {
            show: false
          }
        },
        yAxis: [],
        series: []
      };

      arr.forEach((element, index) => {
        option.series[index] = {
          name: element.year,
          type: 'line',
          smooth: true,
          symbolSize: 16,
          itemStyle: {
            color: this.colors[index]
          },
          tooltip: {
            formatter: function (params, ticket, callback) {
              return `降雨量<br /> ${params.marker}  ${element.year}年${params.name}: ${params.data}mm`;
            }
          },
          lineStyle: {
            width: 4
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: this.colors[index] // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: this.bgColors[index] // 100% 处的颜色
                }
              ],
              global: false // 缺省为 false
            }
          },
          data: element.data
        };
      });

      arr.forEach((element, index) => {
        const current = {
          type: 'bar',
          name: element.year,
          data: element.data,
          itemStyle: {
            color: this.colors[index]
          },
          barWidth: 16
        };
        option.series.push(current);
      });
      option.yAxis[0] = {
        type: 'value',
        min: 0,
        interval: 30,
        axisLabel: {
          formatter: '{value}',
          fontFamily: 'PingFangSC, PingFang SC',
          fontSize: 14,
          color: '#252B46'
        }
      };
      myChart.setOption(option);
      window.addEventListener('resize', function () {
        myChart.resize();
      });
    },
    getchecktype() {
      let that = this;
      sysdictviewlistDictItem({
        dictCode: 'ZD-000004'
      })
        .then((e) => {
          that.checkArr = e.object;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getstationData() {
      let data = {
        currentPage: 1,
        pageSize: 1000
      };
      viewPageStationInfo(data).then((res) => {
        this.stationData = res.object.dataList;
      });
    },

    // 触发搜索按钮
    handleSearch() {
      this.getData();
    },
    typeChange() {
      this.query.stcd = '';
    }
  }
};
</script>

<style lang="less" scoped>
.content-common {
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 25px;
}
.search-top {
  margin-bottom: 20px;
  border-bottom: 2px solid #ebebeb;
}

.header-title {
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 24px;
  color: #252b46;
  line-height: 33px;
  text-align: center;
  font-style: normal;
}
.data-preview {
  display: flex;
  justify-content: space-between;
}
.preview-item {
  width: 711px;
  height: 108px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #252b46;
  line-height: 20px;
  text-align: left;
  font-style: normal;
  padding: 5px 20px 5px 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-button {
    margin-left: 31px;
    width: 68px;
    height: 30px;
    border-radius: 15px;
    color: #fff;
  }
  span {
    //font-family: Impact;
    font-size: 18px;
    font-weight: bold;
    &.total {
      color: #ff7e42;
      line-height: 20px;
    }
  }
}
table {
  border-collapse: collapse;
  border: 1px #525152 solid;
  width: 100%;
  margin: 20px auto;
}
th {
  background-color: #eaeaea;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #262626;
  line-height: 20px;
  text-align: center;
  font-style: normal;
}
th,
td {
  border: 1px #252b46 solid;
  text-align: center;
  font-size: 12px;
}
th {
  height: 52px;
}
td {
  height: 30px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #262626;
  line-height: 20px;
  text-align: center;
  font-style: normal;
}
/* 模拟对角线 */
.oline {
  border-top: 40px #fff solid;
  /*上边框宽度等于表格第一行行高*/
  width: 0px;
  /*让容器宽度为0*/
  height: 0px;
  /*让容器高度为0*/
  border-left: 80px #fff solid;
  /*左边框宽度等于表格第一行第一格宽度*/
  position: relative;
  /*让里面的两个子容器绝对定位*/
}
.oline::before {
  position: absolute;
  top: -52px;
  left: -80px;
  width: 162px;
  height: 52px;
  background: #eaeaea
    url()
    no-repeat 100% center;
  content: '';
}
.span1 {
  font-style: normal;
  display: block;
  position: absolute;
  top: -38px;
  left: 40px;
  width: 35px;
}

.span2 {
  font-style: normal;
  display: block;
  position: absolute;
  top: -25px;
  left: -70px;
  width: 55px;
}
/*模拟对角线*/
.oline {
  border-top: 52px #fff solid;
  /*上边框宽度等于表格第一行行高*/
  width: 0px;
  /*让容器宽度为0*/
  height: 0px;
  /*让容器高度为0*/
  border-left: 80px #ccc solid;
  /*左边框宽度等于表格第一行第一格宽度*/
  position: relative;
  /*让里面的两个子容器绝对定位*/
}
</style>

